﻿using Handday.Erp.Transfer.Enum;
using Handday.Erp.Transfer.Models.EightTradingSource;
using Handday.Erp.Transfer.Repositories;
using HandDay.Framework.Common.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
using Mapster;
using Handday.Erp.Transfer.Entities;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace Handday.Erp.Transfer.Services.Imp
{
    /// <summary>
    /// 8项交易源数据存储
    /// </summary>
    public class EightTradingStorageService : ISourceDataStorageService
    {
        private readonly IEightTradingSourceRepository _eightTradingSourceRepository;
        private readonly ILogger<EightTradingStorageService> _logger;

        /// <summary>
        /// ctor
        /// </summary>
        public EightTradingStorageService(
            IEightTradingSourceRepository eightTradingSourceRepository,
            ILogger<EightTradingStorageService> logger)
        {
            _eightTradingSourceRepository = eightTradingSourceRepository;
            _logger = logger;
        }

        /// <summary>
        /// 功能类型
        /// </summary>
        public ErpFeatureTypeEnum FeatureType => ErpFeatureTypeEnum.EightTrading;

        /// <summary>
        /// 存储
        /// </summary>
        public async Task<ServiceResult> StoreAsync(string jsondata)
        {

            if (!string.IsNullOrWhiteSpace(jsondata))
            {
                var data = JsonSerializer.Deserialize<List<EightTradingSourceAddDto>>(jsondata);
                //过滤数据
                var idList = data.Select(m => m.BillId);
                var existIdList = await _eightTradingSourceRepository.Where(m => idList.Contains(m.BillId)).Select(m => m.BillId).ToListAsync();
                data = data.Where(m => !existIdList.Contains(m.BillId)).ToList();
                if (!data.Any())
                {
                    _logger.LogInformation($"{nameof(EightTradingStorageService)},8项交易源数据为空");
                    return ServiceResult.Succeed();
                }

                var entities = data.Adapt<List<EightTradingSource>>();
                var result = await _eightTradingSourceRepository.BulkAddAsync(entities);
            }

            return ServiceResult.Succeed();
        }
    }
}
